/*
 * monitor.cpp
 *
 *  Created on: 2011-5-30
 *      Author: chenl
 */

#include "monitor.h"
#include "common/common_err.h"
#include "ps_error.h"
#include "processmgt.h"
#include "config.h"
#include <stdio.h>
#include <string.h>


CMonitor::CMonitor(int height, int width, int startY, int startX, const char* szTitle)
	: height_(height), width_(width), startY_(startY), startX_(startX),
	  winContentHeight_(height - 4), winContentWidth_(width - 2), winContentStartY_(startY + 3), winContentStartX_(startX + 1),
	  currY_(winContentStartY_), currX_(winContentStartX_), pWin_(NULL)
{
	snprintf(szTitle_, sizeof(szTitle_), "%s", szTitle);
}

CMonitor::~CMonitor()
{

}

int32_t CMonitor::Initialize()
{
	if (height_ > MAX_ROW)
	{
		return E_PS_CONSOLE_TOOHIGH;
	}
	if (width_ > MAX_COLUMN)
	{
		return E_PS_CONSOLE_TOOWIDE;
	}

	pWin_ = newwin(height_ - 1, width_, startY_ + 1, startX_);
	if (NULL == pWin_)
	{
		return E_PS_INIT_MONITOR_FAIL;
	}
	attron(A_BOLD);
	mvprintw(startY_, startX_, "%s", szTitle_);
	attroff(A_BOLD);
	wborder(pWin_, '|', '|', '-', '-', '+', '+', '+', '+');

	wattron(pWin_, A_STANDOUT);
	switch(GET_PARAMCONFIG_INSTANCE().GetScheduler())
	{
	case enmScheduler_O_N:
		mvwprintw(pWin_, startY_ + 1, startX_ + 1, PCB_INFO_FORMAT_O_N);
		break;
	case enmScheduler_O_1:
		mvwprintw(pWin_, startY_ + 1, startX_ + 1, PCB_INFO_FORMAT_O_1);
		break;
	case enmScheduler_BFS:
	case enmScheduler_CFS:
	default:
		return E_PS_MISCONFIGED;
	}
	wattroff(pWin_, A_STANDOUT);

	pWinContent_ = newwin(winContentHeight_, winContentWidth_, winContentStartY_, winContentStartX_);
	if (NULL == pWinContent_)
	{
		return E_PS_INIT_MONITOR_FAIL;
	}
	wrefresh(pWin_);
	return S_OK;
}

int32_t CMonitor::Uninitialize()
{
	wborder(pWin_, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
	wrefresh(pWin_);
	delwin(pWin_);
	return S_OK;
}

int32_t CMonitor::Update(char arrszContent[][MAX_COLUMN], unsigned lines,  unsigned maxContentLen, int startLineNum, int highlight)
{
	int32_t ret = CheckArea(startLineNum, winContentStartX_, lines, maxContentLen);
	if (0 > ret)
	{
		return ret;
	}

	currY_ = startLineNum;
	for (unsigned i = 0; i < lines; ++i)
	{
		if((int)i == highlight)
			wattron(pWinContent_, A_UNDERLINE);
		mvwprintw(pWinContent_, currY_++, winContentStartX_, arrszContent[i]);
		wattroff(pWinContent_, A_UNDERLINE);
	}
	wrefresh(pWinContent_);
	return S_OK;
}
